<template>
  <div class="functions-settings">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>函数设置</span>
          <el-button type="primary" @click="handleAddFunction">添加函数</el-button>
        </div>
      </template>
      <el-table :data="functions" style="width: 100%" empty-text="暂无数据" v-loading="loading">
        <el-table-column prop="name" label="函数名称" />
        <el-table-column prop="description" label="描述" show-overflow-tooltip />
        <el-table-column prop="type" label="函数类型" width="120">
          <template #default="scope">
            {{functionTypes.find(t => t.code === scope.row.type)?.desc || scope.row.type}}
          </template>
        </el-table-column>
        <el-table-column label="执行前确认" width="120">
          <template #default="scope">
            <el-tag :type="scope.row.needConfirm ? 'warning' : 'info'">
              {{ scope.row.needConfirm ? '需要确认' : '自动执行' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === 'active' ? 'success' : 'info'">
              {{ scope.row.status === 'active' ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="300">
          <template #default="scope">
            <el-button type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="success" size="small" @click="viewParameters(scope.row)">查看参数</el-button>
            <el-button type="warning" size="small" @click="handleTestFunction(scope.row)">测试</el-button>
            <el-button type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 函数添加/编辑对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="720px" destroy-on-close>
      <el-form :model="functionForm" :rules="rules" ref="functionFormRef" label-width="120px">
        <el-form-item label="函数名称" prop="name">
          <el-input v-model="functionForm.name" placeholder="英文名称，用于调用" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="functionForm.description" type="textarea" :rows="3" placeholder="详细描述函数的功能和用途" />
        </el-form-item>
        <el-form-item label="函数类型" prop="type">
          <el-select v-model="functionForm.type" placeholder="选择函数类型">
            <el-option v-for="item in functionTypes" :key="item.code" :label="item.desc" :value="item.code" />
            <el-option v-if="!functionTypes.length" label="通用函数" value="general" />
          </el-select>
        </el-form-item>
        <el-form-item label="参数定义" prop="parameters">
          <el-input v-model="functionForm.parameters" type="textarea" :rows="8"
            placeholder='JSON格式的参数定义，例如：{"properties":{"name":{"type":"string","description":"用户名称"}}}' />
        </el-form-item>
        <el-form-item label="状态">
          <el-switch v-model="functionForm.status" :active-value="'active'" :inactive-value="'inactive'" />
        </el-form-item>
        <el-form-item label="执行前确认">
          <el-switch v-model="functionForm.needConfirm" />
        </el-form-item>
        <el-form-item label="触发前端动作">
          <el-switch v-model="functionForm.triggerFrontend" />
        </el-form-item>
        <el-form-item label="结果返回模型">
          <el-switch v-model="functionForm.returnToModel" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSave">保存</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 参数查看对话框 -->
    <el-dialog v-model="parametersDialogVisible" title="函数参数" width="800px">
      <div v-if="currentFunction">
        <h4>{{ currentFunction.name }}</h4>
        <el-descriptions :column="1" border>
          <el-descriptions-item label="参数定义">
            <pre class="json-viewer">{{ formatJSON(currentFunction.parameters) }}</pre>
          </el-descriptions-item>
        </el-descriptions>
      </div>
    </el-dialog>
  </div>
</template>

<script lang="ts">
import { defineComponent, reactive, ref, onMounted } from 'vue';
import { useFunctionsStore } from '@/store/functions';
import type { CustomFunction } from '@/store/functions';
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus';
import { getFunctionTypes, testFunction } from '@/apis/function';

export default defineComponent({
  name: 'FunctionsSettings',
  setup() {
    const functionsStore = useFunctionsStore();
    const dialogVisible = ref(false);
    const parametersDialogVisible = ref(false);
    const dialogTitle = ref('添加函数');
    const functions = ref<CustomFunction[]>([]);
    const functionFormRef = ref();
    const currentFunction = ref<CustomFunction | null>(null);
    const functionTypes = ref<Array<{ code: string, desc: string }>>([]);
    const loading = ref(false);

    const functionForm = reactive<any>({
      id: '',
      name: '',
      description: '',
      parameters: '',
      status: 'active' as 'active' | 'inactive',
      type: 'general',
      needConfirm: false,
      triggerFrontend: false,
      returnToModel: true
    });

    const rules = {
      name: [
        { required: true, message: "请输入函数名称", trigger: "blur" },
        { pattern: /^[a-zA-Z][a-zA-Z0-9_]*$/, message: "函数名称只能包含字母、数字和下划线，且必须以字母开头", trigger: "blur" }
      ],
      description: [{ required: true, message: "请输入函数描述", trigger: "blur" }],
      type: [{ required: true, message: "请选择函数类型", trigger: "change" }],
      parameters: [
        { required: true, message: "请输入参数定义", trigger: "blur" },
        {
          validator: (rule: any, value: string, callback: any) => {
            if (!value) {
              callback();
              return;
            }
            try {
              JSON.parse(value);
              callback();
            } catch (error) {
              callback(new Error("参数定义必须是有效的JSON格式"));
            }
          },
          trigger: "blur"
        }
      ]
    };

    const handleAddFunction = () => {
      dialogTitle.value = '添加函数';
      functionForm.id = '';
      functionForm.name = '';
      functionForm.description = '';
      functionForm.parameters = '';
      functionForm.status = 'active';
      functionForm.type = 'general';
      functionForm.needConfirm = false;
      functionForm.triggerFrontend = false;
      functionForm.returnToModel = true;
      dialogVisible.value = true;
    };

    const handleEdit = (row: CustomFunction) => {
      dialogTitle.value = '编辑函数';
      functionForm.id = row.id;
      functionForm.name = row.name;
      functionForm.description = row.description;
      functionForm.parameters = typeof row.parameters === 'string' ? row.parameters : JSON.stringify(row.parameters, null, 2);
      functionForm.status = row.status || 'active';
      functionForm.type = row.type || 'general';
      functionForm.needConfirm = Boolean(row.needConfirm);
      functionForm.triggerFrontend = Boolean(row.triggerFrontend);
      functionForm.returnToModel = row.regenerateResult !== undefined ? Boolean(row.regenerateResult) : true;
      dialogVisible.value = true;
    };

    const viewParameters = (row: CustomFunction) => {
      currentFunction.value = row;
      parametersDialogVisible.value = true;
    };

    const handleDelete = async (row: CustomFunction) => {
      ElMessageBox.confirm(`确定要删除函数 "${row.name}" 吗？`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(async () => {
        const loadingInstance = ElLoading.service({ fullscreen: true, text: '删除中...' });
        try {
          await functionsStore.deleteFunction(row.id);
          await fetchFunctions();
          ElMessage.success("删除成功");
        } catch (error) {
          ElMessage.error("删除失败，请重试");
          console.error("删除函数失败:", error);
        } finally {
          loadingInstance.close();
        }
      }).catch(() => {
        // 取消删除
      });
    };

    const handleSave = async () => {
      try {
        if (!functionFormRef.value) return;

        await functionFormRef.value.validate();

        // 检查函数名是否重复
        const existingFunction = functions.value.find(
          f => f.name === functionForm.name && f.id !== functionForm.id
        );
        if (existingFunction) {
          ElMessage.error("函数名称已存在");
          return;
        }

        const loadingInstance = ElLoading.service({ fullscreen: true, text: functionForm.id ? '更新中...' : '添加中...' });

        try {
          // 创建符合CustomFunction接口的数据
          const functionData: CustomFunction = {
            id: functionForm.id,
            name: functionForm.name,
            description: functionForm.description,
            type: functionForm.type || 'general',
            parameters: functionForm.parameters,
            needConfirm: Boolean(functionForm.needConfirm),
            triggerFrontend: Boolean(functionForm.triggerFrontend),
            frontendAction: functionForm.triggerFrontend ? 'default' : null,
            regenerateResult: Boolean(functionForm.returnToModel),
            implementationClass: 'com.government.ai.biz.AiFunctionImplementation',
            implementationMethod: functionForm.name,
            status: functionForm.status
          };

          console.log('保存函数数据:', functionData);

          if (functionForm.id) {
            await functionsStore.updateFunction(functionData);
          } else {
            await functionsStore.createFunction(functionData);
          }

          dialogVisible.value = false;
          await fetchFunctions();
          ElMessage.success(functionForm.id ? "编辑成功" : "添加成功");
        } catch (error) {
          ElMessage.error(functionForm.id ? "编辑失败，请重试" : "添加失败，请重试");
          console.error("保存函数失败:", error);
        } finally {
          loadingInstance.close();
        }
      } catch (error) {
        console.error("表单验证失败:", error);
      }
    };

    const handleTestFunction = async (row: CustomFunction) => {
      try {
        if (!row.name) {
          ElMessage.warning("函数名称不能为空");
          return;
        }

        let testParams: Record<string, any> = {};

        // 尝试解析函数参数，生成测试参数
        try {
          const paramsDef = typeof row.parameters === 'string'
            ? JSON.parse(row.parameters)
            : row.parameters;

          if (paramsDef && paramsDef.properties) {
            for (const key in paramsDef.properties) {
              const prop = paramsDef.properties[key];
              switch (prop.type) {
                case 'string':
                  testParams[key] = '测试值';
                  break;
                case 'number':
                  testParams[key] = 1;
                  break;
                case 'boolean':
                  testParams[key] = true;
                  break;
                case 'array':
                  testParams[key] = [];
                  break;
                case 'object':
                  testParams[key] = {};
                  break;
                default:
                  testParams[key] = null;
              }
            }
          }
        } catch (error) {
          ElMessage.warning("参数解析失败，将使用空参数进行测试");
          console.error("解析参数失败:", error);
        }

        const loadingInstance = ElLoading.service({ fullscreen: true, text: '测试执行中...' });

        try {
          const result = await testFunction(row.name, testParams);
          if (result.code === 200) {
            ElMessageBox.alert(
              `<pre style="white-space: pre-wrap; word-break: break-all;">${result.data}</pre>`,
              '测试结果',
              { dangerouslyUseHTMLString: true }
            );
          } else {
            ElMessage.error(`测试失败: ${result.msg}`);
          }
        } catch (error) {
          ElMessage.error("测试执行失败，请检查函数实现");
          console.error("测试函数失败:", error);
        } finally {
          loadingInstance.close();
        }
      } catch (error) {
        ElMessage.error("测试执行异常");
        console.error("测试执行异常:", error);
      }
    };

    const formatJSON = (jsonData: string | Record<string, any>) => {
      try {
        if (typeof jsonData === 'string') {
          const parsed = JSON.parse(jsonData);
          return JSON.stringify(parsed, null, 2);
        } else {
          return JSON.stringify(jsonData, null, 2);
        }
      } catch (e) {
        return String(jsonData);
      }
    };

    const fetchFunctions = async () => {
      loading.value = true;
      try {
        functions.value = await functionsStore.fetchFunctions();
      } catch (error) {
        ElMessage.error("获取函数列表失败");
        console.error("获取函数列表失败:", error);
      } finally {
        loading.value = false;
      }
    };

    const fetchFunctionTypes = async () => {
      try {
        const response = await getFunctionTypes();
        if (response.code === 200 && response.data) {
          functionTypes.value = response.data;
        }
      } catch (error) {
        console.error("获取函数类型失败:", error);
      }
    };

    onMounted(() => {
      fetchFunctions();
      fetchFunctionTypes();
    });

    return {
      dialogVisible,
      parametersDialogVisible,
      dialogTitle,
      functions,
      functionForm,
      functionFormRef,
      currentFunction,
      functionTypes,
      loading,
      rules,
      handleAddFunction,
      handleEdit,
      viewParameters,
      handleDelete,
      handleSave,
      handleTestFunction,
      formatJSON
    };
  }
});
</script>

<style lang="scss" scoped>
.functions-settings {
  padding: 20px;

  .box-card {
    margin-bottom: 20px;
  }

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .json-viewer {
    background-color: #f5f7fa;
    padding: 10px;
    border-radius: 4px;
    font-family: monospace;
    white-space: pre-wrap;
    max-height: 300px;
    overflow-y: auto;
  }
}
</style>